# amplitude.emailer - a mailer class

import sys, smtplib
from amplitude.dict import Dict

class Emailer(Dict):
    """create and send email using templates
    Params: template_lookup : a Mako template_lookup object
            config : an amplitude.config object
                     config.Email has needed variables
    """
    def __init__(self, config=None, template_lookup=None, **args):
        self.template_lookup = template_lookup
        self.config = config
        Dict.__init__(self, **args)

    def render(self, template_path, **args):
        """render a template at the given path; look it up with self.template_lookup."""
        template = self.template_lookup.get_template(template_path)
        return template.render(c=self, **args)

    def send(self, msg, DEBUG=0):
        """send the given msg to the SMTP server and return the status of the delivery.
        Returns None if delivery succeeded.
        Returns a sys.exc_info() tuple if the SMPT client raised an exception.
        Set optional DEBUG param to 1 to get verbose output from the SMTP server.
        """
        cfg = self.config.Email
        if self.DEBUG == True:
            print 'email config:', cfg
        if cfg.delivery == 'smtp':
            # parse the message and send it
            fromaddr = msg['From']
            tolist = msg.get_all('To') or []
            tolist += msg.get_all('Cc') or []
            tolist += msg.get_all('Bcc') or []
            toaddrs = ', '.join(tolist)
            if self.DEBUG==True:
                DEBUG = 1
                print '  toaddrs:', toaddrs
                print '  fromaddr:', fromaddr
                print '  msg:\n', msg.as_string()
            try:
                if cfg.server is not None:
                    if cfg.port is not None:
                        smtpclient = smtplib.SMTP(cfg.server, cfg.port)
                    else:
                        smtpclient = smtplib.SMTP(cfg.server)
                else:
                    smtpclient = smtplib.SMTP()                
                smtpclient.set_debuglevel(DEBUG)    # non-zero gives us exceptions when emailing.
                if cfg.login is not None and cfg.login.lower().strip() != 'none':
                    smtpclient.login(cfg.username, cfg.password)
                smtpclient.sendmail(fromaddr, toaddrs, msg.as_string())
                smtpclient.quit()
            except:
                print sys.exc_info()
                return sys.exc_info()[1][0]        # return the exception rather than raising it -- the show must go on.
        elif self.config.Email.delivery == 'test':
            # return the message as text that would be sent
            pass
        
